var React = require('react');

module.exports = React.createClass({
	displayName:'PageRouter',
	getInitialState:function(){
		return {

		}
	},
	componentDidMount:function(){
		this._controllers = [];
		this.init();
	},
	init: function (handler){
		handler && handler.call(this);
  		this.change();
  		window.addEventListener('hashchange', function () {
    		this.change();
  		}.bind(this), false);
	},
	change: function (){
		var _hashAry = location.hash.split('?'),
			_path = _hashAry[0],
			_search = _hashAry[1],
			_controllers = this._controllers,
			_controller = null;

		for(var i = 0, _len = _controllers.length; i < _len; i++){
			_controller = _controllers[i];
			if(this.test(_path, _controller.router)){
				_controller.handler.call(this, this.getParam(_path, _controller.router))
			}
		}
	},
	test: function (path, router) {
		if(typeof (router) != 'string'){
			return false;
		}
		if(router == '*'){
			return true;
		}

		var _sReg = '';
		_sReg = router.replace(/\/:\w[^\/]+/g, '\/([^\/]+)');
		_sReg = _sReg.replace(/\//g, '\\/');
		_sReg = '^#' + _sReg + '$';

		var _bReg = Boolean(new RegExp(_sReg).test(path));
		var _bIndex = Boolean(path == '' && router == '/');

		return _bReg || _bIndex;
	},
	getParam: function (path, router){
		var _pathAry = path.split('/'),
			_routerAry = router.split('/'),
			_param = {};

		for(var i = 0, _len = _routerAry.length; i < _len; i++){
			if(/^:\w[\w\d]*$/.test(_routerAry[i])){
				_param[_routerAry[i].replace(/^:/, '')] = _pathAry[i];
			}
		}

		return _param;
	},
	getQuery: function (search){
		var _query = {};
		if(typeof search != 'string'){
			return _query;
		}
		var _sAry = search.split('&');
		for(var i = 0, _len = _sAry.length; i < _len; i++){
			var _aAry = _sAry[i].split('=');
			_query[_aAry[0]] = _aAry[1] || null;
		}

		return _query;
	},
	use: function (handler){
		this._controllers.push({
			router: '*',
			handler: handler
		});
	},
	get: function (router, handler){
		this._controllers.push({
			router: router,
			handler: handler
		});
	},
	error: function (handler){
		this._controllers.push({
			router: undefined,
			handler: handler
		});
	},
	render:function(){
		return (

		);
	}
});
